<template>
  <div class="md:flex">
    <template v-for="(item, index) in growCardList" :key="item.title">
      <Card
        size="small"
        :loading="loading"
        :title="item.title"
        class="md:w-1/4 w-full !md:mt-0 !mt-4 cursor-pointer"
        :class="[index + 1 < 4 && '!md:mr-4']"
        :canExpan="false"
      >
        <div class="py-4 flex md:flex-col">
          <Icon :icon="item.icon" :size="120" />
          <div class="text-2xl text-center">
            <template v-if="item.value > 0">
              {{ item.value }}
              <span class="text-1xl">{{ item.danwei }}</span>
            </template>
            <template v-else>
              <span class="text-lg text-gray-400">暂无数据</span>
            </template>
          </div>
        </div>
        <template #extra>
          <a href="#" style="color: #1951be">@中山医康养</a>
        </template>
      </Card>
    </template>
    <Card title="近一年预约科室占比" size="small" class="md:w-2/4" :loading="loading">
      <div ref="chartRef" class="w-full h-50"></div>
      <template #extra>
        <a href="#" style="color: #1951be">@众阳云健康</a>
      </template>
    </Card>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, Ref, defineProps } from 'vue';
  // import { CountTo } from '/@/components/CountTo';
  import { Icon } from '/@/components/Icon';
  import { Card } from 'ant-design-vue';
  import { useECharts } from '/@/hooks/web/useECharts';
  import type { EChartsOption } from 'echarts';
  import { getNowInfo } from '/@/api/sys/desktopApi';
  import { dailySignsListData } from '/@/api/information/dailySigns';
  const loading = ref(true);
  const growCardList = ref<GrowCardItem[]>();
  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

  interface GrowCardItem {
    icon: string;
    title: string;
    value: number;
    total: number;
    color: string;
    action: string;
    danwei: string;
  }
  const p = defineProps({
    phone: {
      type: String, // 指定 phone 的类型为 String
      required: true, // 标记 phone 为必传 prop
      // 你可以在这里添加更多的验证规则，比如 default, validator 等
      default: '13021646422',
    },
  });
  // console.log('手机号11', p);
  // const phone = '13021646422';
  onMounted(async () => {
    try {
      // 获取当前时间
      const timeNow = new Date();
      // 获取一年前的时间
      const halfYearAgo = new Date(timeNow.getTime() - 12 * 30 * 24 * 60 * 60 * 1000);
      console.log('halfYearAgo', halfYearAgo);
      // 调用异步函数并等待结果
      const data = await getNowInfo({
        phone: p.phone,
        startTime: halfYearAgo.toISOString().split('T')[0],
      });
      loading.value = false;

      // 初始化默认数据
      const defaultList: GrowCardItem[] = [
        {
          title: '实时心率',
          icon: 'xinlv1|svg',
          value: 0,
          danwei: 'bpm',
          total: 120000,
          color: 'green',
          action: '时',
        },
        {
          title: '实时体温',
          icon: 'tiwen|svg',
          value: 0,
          danwei: '℃',
          total: 500000,
          color: 'blue',
          action: '日',
        },
      ];
      growCardList.value = defaultList;

      // 初始化默认图表配置
      const defaultChartOptions: EChartsOption = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'middle',
          textStyle: {
            fontSize: 14,
            color: '#999',
          },
        },
        series: [],
      };

      // 优先从 dailySignsListData 获取最新的实时心率和体温（如果可用），否则使用 getNowInfo 的 data.daily
      try {
        const dsParams = { phone: p.phone };
        const dsRes = await dailySignsListData(dsParams);
  const dsList = dsRes && (dsRes.list || []);
        if (Array.isArray(dsList) && dsList.length) {
          // 按时间降序，取最新一条
          const sortedDs = [...dsList].sort(
            (a, b) => (new Date(b.createTime ?? 0).getTime() as number) - (new Date(a.createTime ?? 0).getTime() as number),
          );
          const latest = sortedDs[0] || {};
          const hr = latest.heartRate || (data && data.daily && data.daily.heartRate) || 0;
          const temp = latest.temperature || (data && data.daily && data.daily.temperature) || 0;
          const dailyDataList: GrowCardItem[] = [
            {
              title: '实时心率',
              icon: 'xinlv1|svg',
              value: hr,
              danwei: 'bpm',
              total: 120000,
              color: 'green',
              action: '时',
            },
            {
              title: '实时体温',
              icon: 'tiwen|svg',
              value: temp,
              danwei: '℃',
              total: 500000,
              color: 'blue',
              action: '日',
            },
          ];
          growCardList.value = dailyDataList;
        } else if (data && data.daily) {
          const dailyDataList: GrowCardItem[] = [
            {
              title: '实时心率',
              icon: 'xinlv1|svg',
              value: data.daily.heartRate || 0,
              danwei: 'bpm',
              total: 120000,
              color: 'green',
              action: '时',
            },
            {
              title: '实时体温',
              icon: 'tiwen|svg',
              value: data.daily.temperature || 0,
              danwei: '℃',
              total: 500000,
              color: 'blue',
              action: '日',
            },
          ];
          growCardList.value = dailyDataList;
        }
      } catch (e) {
        // 如果调用 dailySignsListData 失败，退回到 getNowInfo 返回的数据
        if (data && data.daily) {
          const dailyDataList: GrowCardItem[] = [
            {
              title: '实时心率',
              icon: 'xinlv1|svg',
              value: data.daily.heartRate || 0,
              danwei: 'bpm',
              total: 120000,
              color: 'green',
              action: '时',
            },
            {
              title: '实时体温',
              icon: 'tiwen|svg',
              value: data.daily.temperature || 0,
              danwei: '℃',
              total: 500000,
              color: 'blue',
              action: '日',
            },
          ];
          growCardList.value = dailyDataList;
        }
      }

      // 单独判断并处理预约占比图表数据
      if (data && data.departments && data.departments.length > 0) {
        const chartOptions: EChartsOption = {
          tooltip: {
            trigger: 'item',
          },
          legend: {
            // 调整图例位置，留出更多空间
            left: '55%',
            // 将图例垂直居中改为从顶部开始
            top: '10%',
            // 继续使用滚动类型
            type: 'scroll',
            // 增加图例宽度，确保文本完整显示
            width: 200,
            // 增加图例高度，让更多项可以显示
            height: '80%',
            // 垂直排列
            orient: 'vertical',
            // 优化滚动配置
            pageIconSize: 12,
            pageButtonItemGap: 8,
            pageButtonGap: 8,
            // 控制页面按钮类型
            pageButtonPosition: 'end',
            // 设置图标和文本之间的距离
            itemGap: 10,
            // 文本样式设置
            textStyle: {
              fontSize: 12,
              // 允许文本换行
              width: 180,
              rich: {
                name: {
                  width: 170,
                  align: 'left',
                },
              },
            },
            // 格式化器，使用rich text确保文本正确处理
            formatter: (name: string) => {
              return `{name|${name}}`;
            },
            // 确保滚动功能正常
            pageIconColor: '#aaa',
            pageIconInactiveColor: '#ccc',
            pageTextStyle: {
              color: '#666',
            },
          },
          series: [
            {
              color: ['#5ab1ef', '#b6a2de', '#67e0e3', '#2ec7c9'],
              name: '预约占比',
              type: 'pie',
              // 缩小饼图，为图例留出更多空间
              radius: ['35%', '65%'],
              // 将饼图向左移动更多
              center: ['30%', '50%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2,
              },
              label: {
                show: false,
                position: 'center',
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '12',
                  fontWeight: 'bold',
                },
              },
              labelLine: {
                show: false,
              },
              data: data.departments,
              animationType: 'scale',
              animationEasing: 'exponentialInOut',
              animationDelay: function () {
                return Math.random() * 100;
              },
            },
          ],
          };
          setOptions(chartOptions);
      } else {
        // 如果没有预约占比数据，显示默认空数据图表
        setOptions(defaultChartOptions);
      }

      // 确保图表正确渲染
      setTimeout(() => {
        // 这里可以根据需要添加任何延迟后需要执行的操作
      }, 500);
    } catch (error) {
      // 处理从 getBaseInfo 抛出的错误
      console.error(error);
      loading.value = false;

      // 错误时也显示空数据状态
      growCardList.value = [
        {
          title: '实时心率',
          icon: 'xinlv1|svg',
          value: 0,
          danwei: 'bpm',
          total: 120000,
          color: 'green',
          action: '时',
        },
        {
          title: '实时体温',
          icon: 'tiwen|svg',
          value: 0,
          danwei: '℃',
          total: 500000,
          color: 'blue',
          action: '日',
        },
      ];

      const errorOptions: EChartsOption = {
        title: {
          text: '加载失败',
          left: 'center',
          top: 'middle',
          textStyle: {
            fontSize: 14,
            color: '#ff4d4f',
          },
        },
        series: [],
      };
      setOptions(errorOptions);
    }
  });
</script>
